package com.sora.sora.server.controller;

import com.sora.sora.common.model.param.ArticleParam;
import com.sora.sora.common.model.vo.ArticleVO;
import com.sora.sora.common.model.vo.ResultVO;
import com.sora.sora.common.utils.ResponseResult;
import com.sora.sora.common.service.ArticleService;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(value = "文章版块", tags = "文章版块")
@RestController
@RequestMapping("article")
public class ArticleController {

    @Resource
    ArticleService articleService;

    @Resource
    ResponseResult responseResult;

    @ApiOperation(value = "获得文章总数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "每页查询的字段个数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "int", paramType = "query")
    })
    @GetMapping("/count")
    public ResultVO count(@RequestParam("page") int page, @RequestParam("limit") int limit) {
        return responseResult.ok(articleService.count(page, limit));
    }


    @ApiOperation("进入文章")
    @ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{id}")
    public ResultVO get(@PathVariable("id") int id) {
        ArticleVO articleVO = articleService.getById(id);
        return articleVO == null ? responseResult.faile() : responseResult.ok(articleVO);
    }


    @ApiOperation("为文章点赞")
    @ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{id}/like")
    public ResultVO like(@PathVariable("id") int id) {
        Long i = articleService.like(id);
        return i > 0 ? responseResult.ok() : responseResult.faile();
    }


    @ApiOperation(value = "上传文章")
    @ApiResponses({
            @ApiResponse(code = 200, message = "上传成功"),
            @ApiResponse(code = 1002, message = "上传失败")
    })
    @PostMapping
    public ResultVO upload(@RequestBody @Validated(ArticleParam.CreateArticle.class) ArticleParam param) {
        return articleService.post(param) > 0 ? responseResult.ok() : responseResult.faile("上传失败");
    }


    @ApiOperation(value = "更新文章")
    @PutMapping
    public ResultVO update(@RequestParam("id") int id, @RequestParam("content") String content) {
        return articleService.update(id, content) > 0 ? responseResult.ok() : responseResult.faile("更新失败");
    }


    @ApiOperation(value = "删除文章")
    @ApiImplicitParam(name = "id", value = "要删除的文章id", required = true, dataType = "int", paramType = "query")
    @DeleteMapping
    public ResultVO delete(@RequestParam("id") int id) {
        return articleService.delte(id) > 0 ? responseResult.ok() : responseResult.faile("更新失败");
    }

}
